package com.edu.study.normal;

import java.util.*;

/**
 * @Author: wuzs
 * @Date: 2019/11/25 0:32
 */
public class MenuTree {
    public static void main(String[] args) {
        Set<Menu> menuSet = new LinkedHashSet<>();
        Menu m1 = new Menu();
        m1.setId(1);
        m1.setParentId(0);
        m1.setTitle("人才征集");
        menuSet.add(m1);
        Menu m2 = new Menu();
        m2.setId(2);
        m2.setParentId(0);
        m2.setTitle("后台管理");
        menuSet.add(m2);
        Menu m3 = new Menu();
        m3.setId(3);
        m3.setParentId(1);
        m3.setTitle("新增人才");
        menuSet.add(m3);
        Menu m4 = new Menu();
        m4.setId(4);
        m4.setParentId(1);
        m4.setTitle("新增历史");
        menuSet.add(m4);
        Menu m5 = new Menu();
        m5.setId(5);
        m5.setParentId(3);
        m5.setTitle("人才插入");
        menuSet.add(m5);
        Menu m6 = new Menu();
        m6.setId(6);
        m6.setParentId(2);
        m6.setTitle("用户管理");
        menuSet.add(m6);
        Set<Menu> parentMenu = new LinkedHashSet<>();

        Iterator<Menu> iterator = menuSet.iterator();
        while (iterator.hasNext()) {
            Menu menu = iterator.next();
            if (menu.getParentId() == 0) {
                parentMenu.add(menu);
                iterator.remove();
            }
        }
        Map<Integer, Boolean> flagMap = new LinkedHashMap<>();
        for (Menu menu : parentMenu) {
            cover(menuSet, menu, flagMap);
        }
        System.out.println(menuSet);
        System.out.println(parentMenu);
    }

    public static void cover(Set<Menu> dataSet, Menu curMenu, Map<Integer, Boolean> flagMap) {
        Iterator<Menu> iterator = dataSet.iterator();
        int key = curMenu.getId();
        flagMap.put(key, false);
        while (iterator.hasNext()) {
            if (flagMap.get(key)) {
                iterator = dataSet.iterator();
                flagMap.put(key, false);
            }
            if (iterator.hasNext()) {
                Menu next = iterator.next();
                if (next.getParentId() == curMenu.getId()) {
                    if (curMenu.getChildren() == null) curMenu.setChildren(new ArrayList<>());
                    curMenu.getChildren().add(next);
                    iterator.remove();
                    flagMap.put(key, true);
                    cover(dataSet, next, flagMap);
                }
            }
        }
    }
}
